<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_id;
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate(){
		
		if(!preg_match("/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/",$this->username))
		{
			$this->errorCode = self::ERROR_USERNAME_INVALID;//用户名格式不正确
			return false;
		}

		$user = User::model()->find('email=:username',array(':username'=>$this->username));
		if($user == null){
			$this->errorCode = self::ERROR_USERNAME_INVALID;
			return false;
		}
		if($user->status != User::STAFF_STATUS_NORMAL)
		{
			$this->errorCode = self::ERROR_USERNAME_INVALID;
			return false;
		}
		if(crypt($this->password, $user->password) != $user->password)
		{
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
			return false;
		}
		$this->_id = $user->id;
		//init
		Yii::app()->user->setState('nickname',$user->nickname);
		//获取未读邮件个数
		// $pm_nums = Pm::model()->countBySql(' select count(*) from pm_messages where  to_uid=? AND is_read=? AND `status`=? AND del_status=? ',array($user->id,Pm::PM_READ_STATUS_NO,Pm::PM_STATUS_OK,Pm::PM_DEL_NORMAL));
		// Yii::app()->user->setState('pm_nums',$pm_nums);
		Yii::app()->user->setState('type',$user->type);

		$this->errorCode = self::ERROR_NONE;

        return !$this->errorCode;
	}

	public function getId(){
		return $this->_id;
	}


}